<style lang="less">
@import "../common/common.less";
</style>
<template>
  <div>
    <Card title="导入EXCEL">
      <Row>
        <Upload action=""
                :before-upload="handleBeforeUpload"
                accept=".xls, .xlsx">
          <Button icon="ios-cloud-upload-outline"
                  :loading="uploadLoading"
                  @click="handleUploadFile">打开文件</Button>
        </Upload>
      </Row>
      <Row>
        <i-col span='4'>
          <div class="ivu-upload-list-file"
               v-if="file !== null">
            <Icon type="ios-stats"></Icon>
            {{ file.name }}
            <Icon v-show="showRemoveFile"
                  type="ios-close"
                  class="ivu-upload-list-remove"
                  @click.native="handleRemove()"></Icon>
          </div>
        </i-col>
        <i-col span='20'>
          <transition name="fade">
            <Progress v-if="showProgress"
                      :percent="progressPercent"
                      :stroke-width="2">
              <div v-if="progressPercent == 100">
                <Icon type="ios-checkmark-circle"></Icon>
              </div>
            </Progress>
          </transition>
        </i-col>
      </Row>
    </Card>
    <Card class="margin-top-10"
          v-if="progressPercent== 100">
      <Row>
        <i-col span='4'>
          <transition name="fade">
            <div v-if="progressPercent == 100">
              <Button type="success"
                      @click="uploadBatch">点击开始上传</Button>
            </div>
          </transition>
        </i-col>
        <i-col span='20'>
          <div v-if="uploadPercent == 100">
            <Icon type="ios-checkmark-circle"></Icon>
            <span>上传成功！</span>
          </div>
        </i-col>
      </Row>
    </Card>
    <Row class="margin-top-10">
      <Table :columns="tableTitle"
             :data="tableData"
             :loading="tableLoading"></Table>
    </Row>
  </div>
</template>
<script>
import excel from "@/libs/excel";
export default {
  name: "upload-excel",
  data () {
    return {
      baseUrl: BASEURL,
      uploadLoading: false,
      progressPercent: 0,
      uploadPercent: 0,
      showProgress: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      tableTitle: [],
      tableLoading: false
    };
  },
  methods: {
    initUpload () {
      this.progressPercent = 0;
      this.file = null;
      this.showProgress = false;
      this.loadingProgress = 0;
      this.tableData = [];
      this.tableTitle = [];
    },
    handleUploadFile () {
      this.initUpload();
    },
    handleRemove () {
      this.initUpload();
      this.$Message.info("上传的文件已删除！");
    },
    handleBeforeUpload (file) {
      const fileExt = file.name
        .split(".")
        .pop()
        .toLocaleLowerCase();
      if (fileExt === "xlsx" || fileExt === "xls") {
        this.readFile(file);
        this.file = file;
      } else {
        this.$Notice.warning({
          title: "文件类型错误",
          desc:
            "文件：" +
            file.name +
            "不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。"
        });
      }
      return false;
    },
    // 读取文件
    readFile (file) {
      const reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onloadstart = e => {
        this.uploadLoading = true;
        this.tableLoading = true;
        this.showProgress = true;
      };
      reader.onprogress = e => {
        this.progressPercent = Math.round((e.loaded / e.total) * 100);
      };
      reader.onerror = e => {
        this.$Message.error("文件读取出错");
      };
      reader.onload = e => {
        this.$Message.info("文件读取成功");
        const data = e.target.result;
        const { header, results } = excel.read(data, "array");
        const tableTitle = header.map(item => {
          return { title: item, key: item };
        });
        this.tableData = results;
        //              console.log(results);
        this.tableTitle = tableTitle;
        this.uploadLoading = false;
        this.tableLoading = false;
        this.showRemoveFile = true;
      };
    },
    uploadBatch () {
      let upload_batch_url = this.baseUrl + "/upload_batch";
      let str = JSON.stringify(this.tableData);
      let postData = this.$qs.stringify({
        data: str
      });
      // console.log(str);
      this.$axios({
        url: upload_batch_url,
        method: "post",
        data: postData
      }).then(res => {
        this.$message.success("上传成功！");
      });
    }
  },
  created () { },
  mounted () { }
};
</script>
